package hn.cch.spring_boot_webapps_war;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.File;
import java.io.IOException;
import java.util.Properties;

public class TomcatEnvironmentPostProcessor implements EnvironmentPostProcessor {
    // 日志无效
    // private static Logger logger = LoggerFactory.getLogger(TomcatEnvironmentPostProcessor.class);

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment configurableEnvironment, SpringApplication springApplication) {
        String catalina = System.getProperty("catalina.home");
        // logger.info("catalina.home:" + catalina);
        System.out.println("catalina.home:" + catalina);

        String application = catalina + File.separator + "application.properties";
        File file = new File(application);
        // logger.info("application.path : " + application);
        System.out.println("application.path : " + application);

        if (file.exists()) {
            System.out.println("outside file exist");
            FileSystemResource resource = new FileSystemResource(file);
            try {
                Properties properties = PropertiesLoaderUtils.loadProperties(resource);
                MutablePropertySources propertySources = configurableEnvironment.getPropertySources();
                propertySources.addFirst(new PropertiesPropertySource("config", properties));
                System.out.println("load outside success");
            } catch (Exception e) {
                System.out.println("load outside:" + e.getMessage());
            }
        } else {
            System.out.println("outside is not exist, load inside file");
        }
    }


}
